package com.cloudxingkong.dianyinke.Welcome;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.cloudxingkong.dianyinke.NewTeacher.Ui.Login;
import com.cloudxingkong.dianyinke.NewTeacher.Ui.TeacherMainActivity;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.HttpUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.MD5Utils;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Ui.MainActivity;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.http.cookie.DbCookieStore;
import org.xutils.x;

import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;

/**
 * 电音课 欢迎页
 */
public class WelcomePage extends AppCompatActivity {

	private final int SPLASH_DISPLAY_LENGHT = 2500; // 延迟3秒
	private SharedPreferences preferences;
	private SharedPreferences.Editor editor;

	private double latitude;
	private double longitude;
	public AMapLocationClient mLocationClient = null;
	public AMapLocationClientOption option = null;
	public boolean flag = false;
	public boolean isConn = false;

	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_welcome_page);
		preferences = getSharedPreferences ("data_dyk", 0);

		mLocationClient = new AMapLocationClient (getApplicationContext ());
		mLocationClient.setLocationListener (new AMapLocationListener () {
			@Override
			public void onLocationChanged (AMapLocation aMapLocation) {
				if (aMapLocation != null) {

					/**
					 *  经度2 116.33508737919622
					 维度2 39.84776234243994
					 定位类型 1
					 */

					int locationType = aMapLocation.getLocationType ();
					longitude = aMapLocation.getLongitude ();
					latitude = aMapLocation.getLatitude ();
					String address = aMapLocation.getAddress ();    //地址
					String country = aMapLocation.getCountry ();    //国家
					String province = aMapLocation.getProvince ();   //省
					String city = aMapLocation.getCity ();        //城市
					String district = aMapLocation.getDistrict ();   //城区
					String street = aMapLocation.getStreet ();         //街道
					String streetNum = aMapLocation.getStreetNum ();   //街道门牌号
					String aoiName = aMapLocation.getAoiName ();     //AOI信息
					if (longitude != 0 || latitude != 0) {
						SharedPreferences.Editor edit = preferences.edit ();
						edit.putString ("longitude", longitude + "");
						edit.putString ("latitude", latitude + "");
						edit.putString ("Laddress", address);
						edit.putString ("Lcountry", country + "");
						edit.putString ("Lprovince", province + "");
						edit.putString ("Lcity", city + "");
						edit.putString ("Ldistrict", district + "");
						edit.putString ("Lstreet", street + "");
						edit.putString ("LstreetNum", streetNum + "");
						edit.putString ("LaoiName", aoiName + "");
						edit.commit ();

						String spLongitude = preferences.getString ("longitude", "");
						String spLatitude = preferences.getString ("latitude", "");

						Log.e ("test0", "当前地址: " + address + "\n国家: " + country + "\n省: " + province + "\n城市: " + city + "\n城区: " +
								district + "\n街道: " + street + "\n街道门牌号: " + streetNum + "\nAOI信息: " + aoiName);

						if (spLongitude.equals (longitude + "") && spLatitude.equals (latitude + "")) {
							Log.e ("test", "sp中 经度 " + spLongitude +
									"\nsp中 维度 " + spLatitude + "\n定位类型 " + locationType);
							/*Toast.makeText(WelcomePage.this,"sp中 经度 " + spLongitude +
									"\nsp中 维度 " + spLatitude + "\n定位类型 "+locationType+
                                    "\n当前地址: "+preferences.getString("Laddress", "")+"\n国家: "+preferences.getString("Lcountry", "")+"\n省: "+preferences.getString("Lprovince", "")+
                                    "\n城市: "+preferences.getString("Lcity", "")+"\n城区: "+ preferences.getString("Ldistrict", "")+"\n街道: "+preferences.getString("Lstreet", "")+
                                    "\n街道门牌号: "+preferences.getString("LstreetNum", "")+"\nAOI信息: "+preferences.getString("LaoiName", ""),
                                    Toast.LENGTH_SHORT).show();*/
                            /*Toast.makeText(WelcomePage.this,"sp中 经度 " + spLongitude +
                                            "\nsp中 维度 " + spLatitude + "\n定位类型 "+locationType+
                                            "\n当前地址: "+preferences.getString("Laddress", ""),
                                    Toast.LENGTH_SHORT).show();*/
							return;
						}
						//Toast.makeText(WelcomePage.this, "经度: " + longitude + "\n维度: " + latitude, Toast.LENGTH_SHORT).show();
					}
				} else {
					Log.e ("test", "高德定位错误 : " + aMapLocation.getErrorCode () + " -- " + aMapLocation.getErrorInfo ());
				}
			}
		});
		option = new AMapLocationClientOption ();
		option.setLocationMode (AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
		option.setNeedAddress (true);
		option.setOnceLocation (false);
		option.setWifiActiveScan (true);
		option.setMockEnable (false);
		option.setInterval (Constans.SPLASH_DISPLAY_LENGHT);
		mLocationClient.setLocationOption (option);
		mLocationClient.startLocation ();

		final String memtype = preferences.getString ("memtype", "");


//        if (preferences.getBoolean("firststare", true)) {
//            editor = preferences.edit();
//            //将登录标志位设置为false，下次登录时不在显示首次登录界面
//            editor.putBoolean("firststare", false);
//            editor.commit();
//
//            Intent intent = new Intent();
//            intent.setClass(WelcomePage.this, AndyViewPagerActivity.class);
//            WelcomePage.this.startActivity(intent);
//            WelcomePage.this.finish();
//        } else {
		/**
		 * 如果不是第一次登录要判断sp中是否存在用户名密码，
		 * ~如果有则进行网络请求登录
		 *  ~判断结果
		 *   ~请求成功
		 *    ~判断登陆人类型 并跳到相应首页  ，并更新sessionID
		 *   ~请求失败
		 *    ~进入登录页 提醒用户继续尝试
		 * ~如果没有则进入登陆页 提醒用户登录
		 *
		 * 登录过程在欢迎页下进行，对于用户来说是透明的
		 */
		isConn = HttpUtils.isNetConnected (this);
		if (isConn) {
			tryLogin ();
		} else {
			handler.sendEmptyMessageDelayed (3, 1300);
		}

//        }

	}

	private void tryLogin () {
		String userPhone = preferences.getString ("userPhone", "");
		String userPwd = preferences.getString ("userPwd", "");
		String md5 = MD5Utils.getMD5 (userPwd);
		if (!userPhone.equals ("") && !userPwd.equals ("")) {

			RequestParams params = new RequestParams (ThisUri.SERVER_YUMING + ThisUri.USER_LOGIN);
			params.addBodyParameter ("uname", userPhone);
			params.addBodyParameter ("upwd", md5);

			x.http ().post (params, new Callback.CommonCallback<String> () {
				@Override
				public void onSuccess (String result) {
					Message msg = handler.obtainMessage ();
					msg.what = 2;
					msg.obj = result;
					handler.sendMessageDelayed (msg, 1300);

					DbCookieStore cookieStore = DbCookieStore.INSTANCE;
					List<HttpCookie> cookies = cookieStore.getCookies ();
					for (int i = 0; i < cookies.size (); i++) {
						Log.e ("test", "欢迎页使用xUtils尝试获取cookie " + i + " : " + cookies.get (i));
						SharedPreferences.Editor edit = preferences.edit ();
						edit.putString ("sessionID", cookies.get (i) + "");
						edit.commit ();
					}
				}

				@Override
				public void onError (Throwable ex, boolean isOnCallback) {
					Log.e ("test", "欢迎页登陆失败 " + ex.getMessage ());
					handler.sendEmptyMessageDelayed (1, 1300);
				}

				@Override
				public void onCancelled (CancelledException cex) {

				}

				@Override
				public void onFinished () {

				}
			});

		} else {
			handler.sendEmptyMessageDelayed (0, 2500);
		}
	}

	private Handler handler = new Handler () {
		@Override
		public void handleMessage (Message msg) {
			super.handleMessage (msg);
			switch (msg.what) {
				case 0:
					Toast.makeText (WelcomePage.this, "请登录！", Toast.LENGTH_SHORT).show ();
					startActivity (new Intent (WelcomePage.this, Login.class));
					finish ();
					break;
				case 1:
					Toast.makeText (WelcomePage.this, "登陆失败，请重新尝试", Toast.LENGTH_SHORT).show ();
					startActivity (new Intent (WelcomePage.this, Login.class));
					finish ();
					break;
				case 2:
					String result = (String) msg.obj;
					HashMap<String, Object> login = LoginJsonUtils.getJsonFromLogin (result);
					Object success = login.get ("success");
					flag = (boolean) success;
					if (flag) {
						//请求结果为true
						if (login.get ("memtype").equals ("teacher")) {
							Log.e ("test", "教师登陆成功!");

							Toast.makeText (WelcomePage.this, "欢迎回来~", Toast.LENGTH_SHORT).show ();
							startActivity (new Intent (WelcomePage.this, TeacherMainActivity.class));
							finish ();
						} else if (login.get ("memtype").equals ("student")) {
							Log.e ("test", "学生登陆成功!");

							Toast.makeText (WelcomePage.this, "欢迎回来~", Toast.LENGTH_SHORT).show ();
							startActivity (new Intent (WelcomePage.this, MainActivity.class));
							finish ();
						}
					} else {
						/**
						 * 可以请求到结果  不过success值为false  通常为用户名or密码错误导致
						 * 提醒用户继续登陆
						 */
						Toast.makeText (WelcomePage.this, "登录失败，请检查用户名和密码", Toast.LENGTH_SHORT).show ();
						startActivity (new Intent (WelcomePage.this, Login.class));
						finish ();
					}

					break;
				case 3:
					Toast.makeText (WelcomePage.this, "网络不可用，请检查网络后重试!", Toast.LENGTH_SHORT).show ();
					startActivity (new Intent (WelcomePage.this, Login.class));
					finish ();
					break;

			}

		}
	};
}
